package models

import (
	"errors"
	"fmt"
	"reflect"
	"strings"
	"time"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
)

type Anchor_work_stats struct {
	Id       int64 `orm:"auto"`
	HourId   int64
	AnchorId int64
	Type     int
	Value    string `orm:"size(128)"`
}

type StatType int

const (
	ANCHOR_STAT_TYPE_ONLINE_DURATION_MINUTES        StatType = 1 // 在线时长
	ANCHOR_STAT_TYPE_CALLED_REQUEST_COUNT           StatType = 2 // 被拨打请求次数
	ANCHOR_STAT_TYPE_CALLED_CONNECTED_COUNT         StatType = 3 // 被拨打接通次数
	ANCHOR_STAT_TYPE_INITIATED_CALL_COUNT           StatType = 4 // 主动拨打通话次数
	ANCHOR_STAT_TYPE_INITIATED_CONNECTED_COUNT      StatType = 5 // 主动拨打接通次数
	ANCHOR_STAT_TYPE_CALL_SCORE                     StatType = 6 // 通话积分
	ANCHOR_STAT_TYPE_IM_GIFT_SCORE                  StatType = 7 // IM 聊天礼物积分
	ANCHOR_STAT_TYPE_PRIVATE_MESSAGE_UNLOCKED_COUNT StatType = 8 // 私信解锁人数
)

func init() {
	orm.RegisterModel(new(Anchor_work_stats))
}

// AddAnchor_work_stats insert a new Anchor_work_stats into database and returns
// last inserted Id on success.
func AddAnchor_work_stats(m *Anchor_work_stats) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// AnchorWorkStatAdd 根据当前时间戳生成hourId,根据主播id和统计类型累加统计值，如果存在则更新，不存在则新增记录
func AnchorWorkStatInc(anchorId int64, statsType StatType, addValue int64) error {
	timeUnix := time.Now().Unix()
	hourId := timeUnix - time.Now().Unix()%3600

	// 判断是否存在记录
	o := orm.NewOrm()
	qs := o.QueryTable(new(Anchor_work_stats))
	exist := qs.Filter("HourId", hourId).Filter("AnchorId", anchorId).Filter("Type", int(statsType)).RelatedSel().Exist()
	if exist {
		// 累加
		sql := "UPDATE `anchor_work_stats` SET `value` = `value` + ? WHERE `hour_id` = ? AND `anchor_id` = ? AND `type` = ?"
		_, err := o.Raw(sql, addValue, hourId, anchorId, int(statsType)).Exec()
		if err != nil {
			logs.Error("AnchorWorkStatInc update error: ", err)
			return err // 返回错误信息给调用者
		}
	} else {
		// 新增
		m := Anchor_work_stats{
			HourId:   hourId,
			AnchorId: anchorId,
			Type:     int(statsType),
			Value:    fmt.Sprintf("%d", addValue),
		}
		_, err := o.Insert(&m)
		if err != nil {
			logs.Error("AnchorWorkStatInc Insert error: ", err)
			return err // 返回错误信息给调用者
		}
	}

	return nil
}

// AnchorWorkStatAdd 根据当前时间戳生成hourId,根据主播id和统计类型递减统计值，如果存在则更新，不存在则新增记录
func AnchorWorkStatDec(anchorId int64, statsType StatType, decValue int64) error {
	timeUnix := time.Now().Unix()
	hourId := timeUnix - time.Now().Unix()%3600

	// 判断是否存在记录
	o := orm.NewOrm()
	qs := o.QueryTable(new(Anchor_work_stats))
	exist := qs.Filter("HourId", hourId).Filter("AnchorId", anchorId).Filter("Type", int(statsType)).RelatedSel().Exist()
	if exist {
		// 累加
		sql := "UPDATE `anchor_work_stats` SET `value` = `value` - ? WHERE `hour_id` = ? AND `anchor_id` = ? AND `type` = ?"
		_, err := o.Raw(sql, decValue, hourId, anchorId, int(statsType)).Exec()
		if err != nil {
			logs.Error("AnchorWorkStatDec update error: ", err)
			return err // 返回错误信息给调用者
		}
	} else {
		// 新增
		m := Anchor_work_stats{
			HourId:   hourId,
			AnchorId: anchorId,
			Type:     int(statsType),
			Value:    fmt.Sprintf("%d", decValue),
		}
		_, err := o.Insert(&m)
		if err != nil {
			logs.Error("AnchorWorkStatDec Insert error: ", err)
			return err // 返回错误信息给调用者
		}
	}

	return nil
}

// GetAnchor_work_statsById retrieves Anchor_work_stats by Id. Returns error if
// Id doesn't exist
func GetAnchor_work_statsById(id int64) (v *Anchor_work_stats, err error) {
	o := orm.NewOrm()
	v = &Anchor_work_stats{Id: id}
	if err = o.QueryTable(new(Anchor_work_stats)).Filter("Id", id).RelatedSel().One(v); err == nil {
		return v, nil
	}
	return nil, err
}

// GetAllAnchor_work_stats retrieves all Anchor_work_stats matches certain condition. Returns empty list if
// no records exist
func GetAllAnchor_work_stats(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Anchor_work_stats))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []Anchor_work_stats
	qs = qs.OrderBy(sortFields...).RelatedSel()
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// UpdateAnchor_work_stats updates Anchor_work_stats by Id and returns error if
// the record to be updated doesn't exist
func UpdateAnchor_work_statsById(m *Anchor_work_stats) (err error) {
	o := orm.NewOrm()
	v := Anchor_work_stats{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteAnchor_work_stats deletes Anchor_work_stats by Id and returns error if
// the record to be deleted doesn't exist
func DeleteAnchor_work_stats(id int64) (err error) {
	o := orm.NewOrm()
	v := Anchor_work_stats{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&Anchor_work_stats{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}
